package com.nxxskj.alcohol.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nxxskj.alcohol.bean.Record;
import com.nxxskj.alcohol.bean.Role;
import com.nxxskj.alcohol.bean.User;
import com.nxxskj.alcohol.service.RecordService;
import com.nxxskj.alcohol.service.RoleService;
import com.nxxskj.alcohol.service.UserService;
import com.nxxskj.common.model.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/")
public class LoginController {


    @Autowired
    private UserService userService;
    @Autowired
    private RecordService recordService;

    @Autowired
    private RoleService roleService;


    @RequestMapping("/")
    public String index() {
        return "login";
    }

    @RequestMapping("login.do")
    public String login() {
        return "login";
    }

    @RequestMapping("dologin.do")
    @ResponseBody
    public RestResponse dologin(String username, String password, HttpSession session) {

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(wp -> wp.eq(User::getUserName, username).or().eq(User::getPhone, username));
        wrapper.eq(User::getPassword, password);
        User user = userService.getOne(wrapper, false);
        if (user != null) {
            session.setAttribute("user", user);
            return RestResponse.success();
        } else {
            return RestResponse.error();
        }
    }

    @RequestMapping("index.do")
    public String goIndex(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute("user");
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getReportTo, user.getRole());
        boolean admin = roleService.count(wrapper) > 0;
        if (admin) {
            long count = recordService.getWaitDealRecordCount(user);
            request.setAttribute("count", count);
        }
        request.setAttribute("admin", admin);
        return "index";
    }

    @RequestMapping("plain.do")
    public String plain() {
        return "plain";
    }


    @RequestMapping("logout.do")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return "redirect:/login.do";
    }


}
